﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager
{
    public partial class MasterLogin : Telerik.Web.UI.RadAjaxPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                System.Web.Security.FormsAuthentication.SignOut();
                Session.Abandon();
                Response.Cookies.Clear();

                Response.Cookies.Add(new HttpCookie("Logo", "Default.png"));
                Response.Cookies.Add(new HttpCookie("Login", "MasterLogin"));
            }

           
            
        }

        protected void btnEnter_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtUsername.Text) && !string.IsNullOrEmpty(txtPassword.Text))
            {

                GPSTrackingDBV2.Entities.Masters MasterEntity = GPSTrackingDBV2.Data.DataRepository.MastersProvider.GetByMasterUsername(txtUsername.Text);
                
                string MasterUsername;
             
                MasterUsername = txtUsername.Text;
                MasterEntity = GPSTrackingDBV2.Data.DataRepository.MastersProvider.GetByMasterUsername(MasterUsername);

                if (MasterEntity != null)
                {
                    string pwd = EncryptaionManager.EncryptionManager.Encrypt(txtPassword.Text, new System.Security.Cryptography.SHA256CryptoServiceProvider());
                    if (MasterEntity.Password == pwd && MasterEntity.IsActive)
                    {
                        SessionManager objSessionManager = new SessionManager();
                        objSessionManager.MasterUsername = MasterUsername;
                        objSessionManager.IsMaster = true;
                        objSessionManager.IsAdmin = false;
                        objSessionManager.IsUser = false;                        

                        HttpContext.Current.Session["SessionManager"] = objSessionManager;

                        System.Web.Security.FormsAuthentication.SetAuthCookie(txtUsername.Text, false);
                        Response.Redirect("Manager/Pages/WebDesktop.aspx");
                    }
                    else
                        showErrorMessage("La contraseña no es correcta o el master no esta activo");

                }
                else
                    showErrorMessage("El master no existe en la base de datos");                    
            }
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Compañías...');", true);
        }
    }
}